/**
 * @file storage_thread.c
 * @brief 存储管理线程实现
 */

#include "action_camera.h"
#include <unistd.h>

/**
 * @brief 存储管理线程主函数
 * @param arg 线程参数
 * @return NULL
 */
void* storage_manager_thread(void* arg) {
    thread_id_t* tid = (thread_id_t*)arg;
    message_t msg;
    shared_frame_t* frame;
    FILE* video_file = NULL;
    uint32_t file_frame_count = 0;
    uint64_t file_size = 0;
    bool recording = false;
    
    // 验证线程ID的有效性
    if (!tid || *tid >= MAX_THREADS) {
        printf("[ERROR] Storage thread: Invalid thread ID pointer or value: tid=%p, value=%u\n", 
               (void*)tid, tid ? (unsigned)*tid : 999);
        return NULL;
    }
    
    printf("[DEBUG] Storage thread started with valid ID: %u (pointer=%p)\n", (unsigned)*tid, (void*)tid);
    
    LOG_INFO("Storage manager thread started", 0);
    atomic_fetch_add(&g_camera_system.sync.active_threads, 1);
    
    while (atomic_load(&g_camera_system.sync.system_running)) {
        update_thread_heartbeat(*tid);
        
        // 接收消息
        if (message_queue_receive(&g_camera_system.message_queues[*tid], &msg, 100) == 0) {
            if (msg.type == MSG_SHUTDOWN) {
                LOG_INFO("Storage thread received shutdown message", 0);
                break;
            }
            
            if (msg.type == MSG_VIDEO_FRAME) {
                memcpy(&frame, msg.data, sizeof(void*));
                
                // 如果没有在录制，开始新的录制文件
                if (!recording) {
                    // 生成文件名
                    time_t now = time(NULL);
                    struct tm* tm_info = localtime(&now);
                    // 安全地生成文件名，确保不超过MAX_FILENAME_LEN
                    snprintf(g_camera_system.current_filename, 
                            MAX_FILENAME_LEN,
                            "%sVID_%04d%02d%02d_%02d%02d%02d.mp4",
                            (g_camera_system.config.storage_path && strlen(g_camera_system.config.storage_path) < MAX_FILENAME_LEN - 25) ? 
                            g_camera_system.config.storage_path : "", // 防止存储路径过长
                            tm_info->tm_year + 1900,
                            tm_info->tm_mon + 1,
                            tm_info->tm_mday,
                            tm_info->tm_hour,
                            tm_info->tm_min,
                            tm_info->tm_sec);
                    
                    video_file = fopen(g_camera_system.current_filename, "wb");
                    if (!video_file) {
                        LOG_ERROR("Failed to create video file: %s", 
                                 g_camera_system.current_filename);
                        frame_pool_release(&g_camera_system.frame_pool, frame);
                        continue;
                    }
                    
                    recording = true;
                    file_frame_count = 0;
                    file_size = 0;
                    g_camera_system.state = SYSTEM_RECORDING;
                    
                    LOG_INFO("Started recording: %s", g_camera_system.current_filename);
                }
                
                // 写入视频数据
                if (video_file) {
                    // 模拟写入编码后的数据
                    size_t bytes_written = fwrite(frame->data, 1, frame->size, video_file);
                    if (bytes_written != frame->size) {
                        LOG_ERROR("Failed to write video data", 0);
                    } else {
                        file_size += bytes_written;
                        file_frame_count++;
                        g_camera_system.stats.bytes_written += bytes_written;
                        
                        LOG_DEBUG("Wrote frame %u, size: %u bytes", 
                                 frame->frame_id, frame->size);
                    }
                    
                    // 定期同步到磁盘
                    if (file_frame_count % 30 == 0) {
                        fflush(video_file);
                        fsync(fileno(video_file));
                    }
                }
                
                // 释放帧缓冲区
                frame_pool_release(&g_camera_system.frame_pool, frame);
                
                // 检查文件大小限制
                if (file_size > g_camera_system.config.max_file_size_mb * 1024 * 1024) {
                    LOG_INFO("File size limit reached, closing current file", 0);
                    
                    if (video_file) {
                        fclose(video_file);
                        video_file = NULL;
                    }
                    
                    recording = false;
                    g_camera_system.state = SYSTEM_IDLE;
                    
                    LOG_INFO("Recording completed: %s (%u frames, %lu bytes)",
                            g_camera_system.current_filename, 
                            file_frame_count, file_size);
                }
            }
            
            if (msg.type == MSG_AUDIO_FRAME) {
                // 处理音频数据
                if (recording && video_file) {
                    // 在实际实现中，这里需要将音频数据复用到MP4容器中
                    LOG_DEBUG("Audio frame received, size: %u", msg.data_size);
                }
            }
            
            if (msg.type == MSG_CONTROL) {
                // 处理控制命令
                char* command = (char*)msg.data;
                if (strcmp(command, "start_recording") == 0) {
                    LOG_INFO("Received start recording command", 0);
                    // 强制开始录制
                } else if (strcmp(command, "stop_recording") == 0) {
                    LOG_INFO("Received stop recording command", 0);
                    if (video_file) {
                        fclose(video_file);
                        video_file = NULL;
                        recording = false;
                        g_camera_system.state = SYSTEM_IDLE;
                    }
                }
            }
        }
    }
    
    // 清理工作
    if (video_file) {
        fclose(video_file);
        LOG_INFO("Recording completed: %s (%u frames, %lu bytes)",
                g_camera_system.current_filename, file_frame_count, file_size);
    }
    
    LOG_INFO("Storage manager thread exiting", 0);
    atomic_fetch_sub(&g_camera_system.sync.active_threads, 1);
    g_camera_system.threads[*tid].status = THREAD_TERMINATED;
    
    return NULL;
}

/**
 * @brief UI管理线程主函数
 * @param arg 线程参数
 * @return NULL
 */
void* ui_manager_thread(void* arg) {
    thread_id_t* tid = (thread_id_t*)arg;
    message_t msg;
    shared_frame_t* preview_frame = NULL;
    uint32_t ui_update_count = 0;
    
    // 验证线程ID的有效性
    if (!tid || *tid >= MAX_THREADS) {
        printf("[ERROR] UI thread: Invalid thread ID pointer or value: tid=%p, value=%u\n", 
               (void*)tid, tid ? (unsigned)*tid : 999);
        return NULL;
    }
    
    printf("[DEBUG] UI thread started with valid ID: %u (pointer=%p)\n", (unsigned)*tid, (void*)tid);
    
    LOG_INFO("UI manager thread started", 0);
    atomic_fetch_add(&g_camera_system.sync.active_threads, 1);
    
    // 模拟UI初始化
    usleep(100000); // 100ms初始化时间
    
    while (atomic_load(&g_camera_system.sync.system_running)) {
        update_thread_heartbeat(*tid);
        
        // 接收消息
        if (message_queue_receive(&g_camera_system.message_queues[*tid], &msg, 50) == 0) {
            if (msg.type == MSG_SHUTDOWN) {
                LOG_INFO("UI thread received shutdown message", 0);
                break;
            }
            
            if (msg.type == MSG_VIDEO_FRAME) {
                // 释放之前的预览帧
                if (preview_frame) {
                    frame_pool_release(&g_camera_system.frame_pool, preview_frame);
                }
                
                // 获取新的预览帧
                memcpy(&preview_frame, msg.data, sizeof(void*));
                
                LOG_DEBUG("UI received preview frame %u", preview_frame->frame_id);
            }
            
            if (msg.type == MSG_USER_INPUT) {
                // 处理用户输入
                char* input = (char*)msg.data;
                LOG_INFO("User input received: %s", input);
                
                // 发送控制命令到存储线程
                if (strcmp(input, "record") == 0) {
                    message_t control_msg = {
                        .type = MSG_CONTROL,
                        .timestamp = get_system_timestamp(),
                        .source_thread = *tid,
                        .dest_thread = THREAD_STORAGE,
                        .data_size = strlen("start_recording") + 1
                    };
                    strcpy((char*)control_msg.data, "start_recording");
                    
                    message_queue_send(&g_camera_system.message_queues[THREAD_STORAGE], 
                                      &control_msg);
                }
            }
        }
        
        // 模拟UI更新 (30fps)
        ui_update_count++;
        
        // 模拟绘制界面
        if (ui_update_count % 30 == 0) {
            LOG_DEBUG("UI update: frames captured: %lu, encoded: %lu, dropped: %lu",
                     g_camera_system.stats.frames_captured,
                     g_camera_system.stats.frames_encoded,
                     g_camera_system.stats.frames_dropped);
        }
        
        usleep(33000); // 30fps UI更新
    }
    
    // 清理预览帧
    if (preview_frame) {
        frame_pool_release(&g_camera_system.frame_pool, preview_frame);
    }
    
    LOG_INFO("UI manager thread exiting", 0);
    atomic_fetch_sub(&g_camera_system.sync.active_threads, 1);
    g_camera_system.threads[*tid].status = THREAD_TERMINATED;
    
    return NULL;
}

/**
 * @brief 网络服务线程主函数
 * @param arg 线程参数  
 * @return NULL
 */
void* network_service_thread(void* arg) {
    thread_id_t* tid = (thread_id_t*)arg;
    message_t msg;
    bool wifi_connected = false;
    uint32_t connection_attempts = 0;
    
    // 验证线程ID的有效性
    if (!tid || *tid >= MAX_THREADS) {
        printf("[ERROR] Network thread: Invalid thread ID pointer or value: tid=%p, value=%u\n", 
               (void*)tid, tid ? (unsigned)*tid : 999);
        return NULL;
    }
    
    printf("[DEBUG] Network thread started with valid ID: %u (pointer=%p)\n", (unsigned)*tid, (void*)tid);
    
    LOG_INFO("Network service thread started", 0);
    atomic_fetch_add(&g_camera_system.sync.active_threads, 1);
    
    // 检查WiFi是否启用
    if (!g_camera_system.config.wifi_enabled) {
        LOG_INFO("WiFi disabled, network thread going to sleep", 0);
        while (atomic_load(&g_camera_system.sync.system_running)) {
            if (message_queue_receive(&g_camera_system.message_queues[*tid], &msg, 1000) == 0) {
                if (msg.type == MSG_SHUTDOWN) {
                    break;
                }
            }
            update_thread_heartbeat(*tid);
        }
        goto exit;
    }
    
    while (atomic_load(&g_camera_system.sync.system_running)) {
        update_thread_heartbeat(*tid);
        
        // 检查消息
        if (message_queue_receive(&g_camera_system.message_queues[*tid], &msg, 100) == 0) {
            if (msg.type == MSG_SHUTDOWN) {
                LOG_INFO("Network thread received shutdown message", 0);
                break;
            }
            
            if (msg.type == MSG_VIDEO_FRAME) {
                // 处理流媒体数据
                if (wifi_connected) {
                    LOG_DEBUG("Streaming frame to network clients", 0);
                }
            }
        }
        
        // 模拟WiFi连接管理
        if (!wifi_connected && connection_attempts < 5) {
            LOG_INFO("Attempting to connect to WiFi (attempt %u)", 
                    connection_attempts + 1);
            
            // 模拟连接过程
            usleep(500000); // 500ms连接时间
            
            if (connection_attempts == 2) { // 第3次尝试成功
                wifi_connected = true;
                LOG_INFO("WiFi connected successfully", 0);
            } else {
                connection_attempts++;
                LOG_WARN("WiFi connection failed, retrying...", 0);
            }
        }
        
        // 模拟HTTP服务器处理
        if (wifi_connected) {
            // 处理HTTP请求
            usleep(10000); // 10ms处理时间
        }
        
        usleep(100000); // 100ms主循环间隔
    }
    
exit:
    if (wifi_connected) {
        LOG_INFO("Disconnecting from WiFi", 0);
        wifi_connected = false;
    }
    
    LOG_INFO("Network service thread exiting", 0);
    atomic_fetch_sub(&g_camera_system.sync.active_threads, 1);
    g_camera_system.threads[*tid].status = THREAD_TERMINATED;
    
    return NULL;
}